import React, { Component } from "react";
// import axios from "axios";
import PubSub from "pubsub-js";

export default class Search extends Component {
    search = async () => {
        // 连续解构赋值+重命名，最终只定义了keyword变量
        const {
            keywordElement: { value: keyword },
        } = this;

        if (keyword.trim().length === 0) {
            alert("请输入待搜索的用户名！");
            return;
        }

        PubSub.publish("updateList", { isFirst: false, isLoading: true });

        // 使用fetch发送请求（未优化）
        // fetch(`https://api.github.com/search/users?q=${keyword.trim()}`)
        //     .then(
        //         (response) => {
        //             console.log("联系服务器成功了", response);

        //             return response.json();
        //         },
        //         (error) => {
        //             console.error("联系服务器失败了", error);
        //             PubSub.publish("updateList", { err: error });
        //             // 返回新的Pending状态的Promise实例，使后续then不再进入onfulfilled回调方法
        //             return new Promise(() => {});
        //         }
        //     )
        //     .then(
        //         (response) => {
        //             console.log("获取数据成功了", response);

        //             // const newTotalUser = response.total_count;

        //             const newUsers = response.items.map((u) => {
        //                 return {
        //                     id: u.id,
        //                     avatarUrl: u.avatar_url,
        //                     username: u.login,
        //                     url: u.html_url,
        //                 };
        //             });

        //             PubSub.publish("updateList", { users: newUsers });
        //         },
        //         (error) => {
        //             console.error("获取数据失败了", error);
        //             PubSub.publish("updateList", { err: error });
        //             return new Promise(() => {});
        //         }
        //     )
        //     .finally(() => {
        //         PubSub.publish("updateList", { isLoading: false });
        //     });

        // 使用fetch发送请求（优化）
        try {
            const response = await fetch(
                `https://api.github.com/search/users?q=${keyword.trim()}`
            );
            const data = await response.json();

            const newUsers = data.items.map((u) => {
                return {
                    id: u.id,
                    avatarUrl: u.avatar_url,
                    username: u.login,
                    url: u.html_url,
                };
            });

            PubSub.publish("updateList", { users: newUsers });
        } catch (error) {
            console.error("获取数据失败了", error);
            PubSub.publish("updateList", { err: error });
        } finally {
            PubSub.publish("updateList", { isLoading: false });
        }
    };

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索Github用户</h3>
                <div>
                    <input
                        ref={(c) => (this.keywordElement = c)}
                        type="text"
                        placeholder="输入关键词点击搜索"
                    />
                    &nbsp;<button onClick={this.search}>搜索</button>
                </div>
            </section>
        );
    }
}
